from fastapi import APIRouter

import akshare as ak
import pandas as pd
import pathlib 


BASE_DIR = pathlib.Path("./data_file/")
data_loader_router=APIRouter(tags=["Load Stock Data"])


@data_loader_router.post("/items/{item_id}")
async def create_item(item_id: int):
    data_file_dir = pathlib.Path("./data_file/")
    return {"data_file_dir": data_file_dir.absolute(),"BASE_DIR":BASE_DIR}

@data_loader_router.post("/get_stock_data")
async def load_stock_data(stock_codes:list[str],
                          start_date:str = "20100101",
                          end_date:str = "20250601"):
    data_file_dir = pathlib.Path("./data_file/")
    data_file_dir.mkdir(parents=True,exist_ok=True)

    for code in stock_codes:
        data_file_name=f"./data_file/{code}_daily_{start_date}_to_{end_date}"
        if pathlib.Path(data_file_name).exists():
            print(f"{code} file already exists!")
            continue
        data = ak.stock_zh_a_hist(
            symbol=code,
            period="daily",
            start_date=start_date,
            end_date=end_date,
            adjust="qfq"
        )
        if not data.empty:
            data.to_csv(data_file_name,index=True,encoding="utf-8")
            print(f"{code} data saved!")
    return 